﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Animation;

namespace G.Controls
{
    public partial class TextPageControl : UserControl
    {
        public TextPageControl()
        {
            InitializeComponent();

        }
        /// <summary>
        /// 前一页
        /// </summary>
        public event EventHandler OnPreviewCharpter;
        /// <summary>
        /// 下一页
        /// </summary>
        public event EventHandler OnNextCharpter;

        public event EventHandler PageIndexChanged;
        /// <summary>
        /// 页面数
        /// </summary>
        public int PageCount
        {
            get
            {
                return pages.Count;
            }
        }
        int pageIndex = -1;
        public int PageIndex
        {
            get
            {
                return pageIndex;
            }
            set
            {
                int temp = 0;
                if (value < 0)
                    temp = 0;
                else if (value >= PageCount)
                    temp = PageCount - 1;
                else
                    temp = value;
                if (temp != pageIndex)
                {
                    txtCenter.Text = pages[temp];
                    if (temp > 0)
                        txtLeft.Text = pages[temp - 1];
                    else if (temp == 0)
                        txtLeft.Text = string.Empty;

                    if (temp < PageCount - 1)
                        txtRight.Text = pages[temp + 1];
                    else if (temp == PageCount - 1)
                        txtRight.Text = string.Empty;

                    if (temp < pageIndex)
                    {
                        Storyboard story = new Storyboard();
                        foreach (TextBlock txt in txtPanel.Children)
                        {
                            var transForm = txt.RenderTransform as System.Windows.Media.TranslateTransform;
                            transForm.X = -(480 - transForm.X);
                            DoubleAnimation da = new DoubleAnimation();
                            da.Duration = new Duration(TimeSpan.FromSeconds(0.4));
                            da.To = 0;
                            Storyboard.SetTarget(da, transForm);
                            Storyboard.SetTargetProperty(da, new PropertyPath("X"));
                            story.Children.Add(da);
                        }
                        story.Begin();
                    }
                    else if (temp > pageIndex)
                    {
                        Storyboard story = new Storyboard();
                        foreach (TextBlock txt in txtPanel.Children)
                        {
                            var transForm = txt.RenderTransform as System.Windows.Media.TranslateTransform;
                            transForm.X = (480 - transForm.X);
                            DoubleAnimation da = new DoubleAnimation();
                            da.Duration = new Duration(TimeSpan.FromSeconds(0.4));
                            da.To = 0;
                            Storyboard.SetTarget(da, transForm);
                            Storyboard.SetTargetProperty(da, new PropertyPath("X"));
                            story.Children.Add(da);
                        }
                        story.Begin();
                    }
                    pageIndex = temp;

                    if (PageIndexChanged != null)
                    {
                        PageIndexChanged(this, EventArgs.Empty);
                    }
                }
                else
                {
                    Storyboard story = new Storyboard();
                    foreach (TextBlock txt in txtPanel.Children)
                    {
                        var transForm = txt.RenderTransform as System.Windows.Media.TranslateTransform;
                        DoubleAnimation da = new DoubleAnimation();
                        da.Duration = new Duration(TimeSpan.FromSeconds(0.2));
                        da.To = 0;
                        Storyboard.SetTarget(da, transForm);
                        Storyboard.SetTargetProperty(da, new PropertyPath("X"));
                        story.Children.Add(da);
                    }
                    story.Begin();
                }
            }
        }

        List<string> pages = new List<string>();
        public void PageText(System.IO.Stream textStream, int fontSize, double readPercent)
        {
            PageText(textStream, fontSize);
            PageIndex = (int)(readPercent * PageCount);
        }
        private void PageText(System.IO.Stream textStream, int fontSize)
        {
            pageIndex = 0;
            this.txtPanel.Clip = new System.Windows.Media.RectangleGeometry() { Rect = new Rect(0, 0, this.ActualWidth, this.ActualHeight) };
            txtMeasure.Visibility = System.Windows.Visibility.Visible;
            txtMeasure.FontSize = fontSize;
            //设置阅读文本大小
            txtLeft.Width = txtRight.Width = txtCenter.Width = this.ActualWidth - 48;
            txtLeft.Height = txtRight.Height = txtCenter.Height = this.ActualHeight;
            this.FontSize = fontSize;
            Canvas.SetLeft(txtLeft, -txtLeft.Width);
            Canvas.SetLeft(txtCenter, 24);
            Canvas.SetLeft(txtRight, this.ActualWidth);


            List<string> lines = new List<string>();
            pageIndex = -1;
            pages.Clear();
            Dictionary<char, double> characterWidths = new Dictionary<char, double>();
            double characterHeight;

            characterWidths.Add(' ', -1);
            using (var reader = new System.IO.StreamReader(textStream))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    lines.Add(line);
                    lines.Add(" ");
                    for (int i = 0; i < line.Length; i++)
                    {
                        if (!characterWidths.ContainsKey(line[i]))
                            characterWidths.Add(line[i], -1);
                    }
                }
            }
            char[] chars = new char[characterWidths.Keys.Count];
            characterWidths.Keys.CopyTo(chars, 0);
            characterHeight = -1;
            foreach (char c in chars)
            {
                this.txtMeasure.Text = c.ToString();
                characterWidths[c] = this.txtMeasure.ActualWidth;
                if (characterHeight == -1 && !Char.IsWhiteSpace(c))
                    characterHeight = this.txtMeasure.ActualHeight;
            }
            System.Text.StringBuilder strbuilder = new System.Text.StringBuilder();
            System.Text.StringBuilder pageString = new System.Text.StringBuilder();
            double lineWidth = 0;
            double lineHeight = 0;
            int pageCount = 1;
            foreach (var line in lines)
            {
                foreach (var c in line)
                {
                    lineWidth += characterWidths[c];
                    if (lineWidth > this.txtCenter.Width)
                    {
                        lineHeight += characterHeight;
                        if (lineHeight > this.ActualHeight)
                        {
                            pageCount++;
                            lineHeight = characterHeight;
                            pages.Add(pageString.ToString());
                            pageString.Clear();
                        }
                        pageString.AppendLine(strbuilder.ToString());
                        strbuilder.Clear();
                        lineWidth = characterWidths[c];
                    }
                    strbuilder.Append(c);
                }
                if (strbuilder.Length > 0)
                {
                    lineHeight += characterHeight;
                    if (lineHeight > this.ActualHeight)
                    {
                        pageCount++;
                        lineHeight = characterHeight;
                        pages.Add(pageString.ToString());
                        pageString.Clear();
                    }
                    pageString.AppendLine(strbuilder.ToString());
                    strbuilder.Clear();
                    lineWidth = 0;
                }
            }
            string text = pageString.ToString();
            if (text.Length > 0 && !string.IsNullOrWhiteSpace(text))
            {
                pageCount++;
                pages.Add(text);
            }
            txtMeasure.Visibility = System.Windows.Visibility.Collapsed;
        }

        public void PageText(System.IO.Stream textStream, int fontSize, int page_Index)
        {
            PageText(textStream, fontSize);
            PageIndex = page_Index;
        }

        protected override void OnManipulationStarted(System.Windows.Input.ManipulationStartedEventArgs e)
        {
            base.OnManipulationStarted(e);

        }
        public void On_ManipulationDelta(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            this.OnManipulationDelta(e);
        }
        protected override void OnManipulationDelta(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            base.OnManipulationDelta(e);
            double x = e.CumulativeManipulation.Translation.X;

            foreach (TextBlock txt in txtPanel.Children)
            {
                (txt.RenderTransform as System.Windows.Media.TranslateTransform).X = x;
            }

        }
        private const double threold = 80;
        public void On_ManipulationCompleted(System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            this.OnManipulationCompleted(e);
        }
        protected override void OnManipulationCompleted(System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            base.OnManipulationCompleted(e);
            double x = e.TotalManipulation.Translation.X;

            if (Math.Abs(x) >= threold)
            {
                if (x < 0 && PageIndex == PageCount - 1)//往左滑
                {
                    //下一张
                    if (OnNextCharpter != null)
                    {
                        OnNextCharpter(this, EventArgs.Empty);
                    }
                    return;
                }

                if (x > 0 && PageIndex == 0)//往右滑
                {
                    //上一章
                    if (OnPreviewCharpter != null)
                    {
                        OnPreviewCharpter(this, EventArgs.Empty);
                    }
                    return;
                }

                //double to = 0;
                if (x > 0)
                {
                    //to = this.ActualWidth;
                    PageIndex--;
                }
                else if (x < 0)
                {
                    //to = -this.ActualWidth;
                    PageIndex++;
                }
            }
            else
            {
                PageIndex = PageIndex;
            }
        }
    }
}
